package com.mediacloud.app.newsmodule.activity;


import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.fragment.app.FragmentTransaction;

import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.chinamcloud.collect.AcquisitionManager;
import com.google.android.exoplayer.SampleHolder;
import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.util.DateParse;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.cloud.ijkplayersdk.obj.AdItem;
import com.mediacloud.app.cloud.ijkplayersdk.untils.Tools;
import com.mediacloud.app.cloud.ijkplayersdk.video.VideoPlayer;
import com.mediacloud.app.cloud.ijkplayersdk.video.inter.AdCliclkListenter;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.addnewslike.p.NewsLikePresenter;
import com.mediacloud.app.model.utils.NeedTokenType;
import com.mediacloud.app.newsmodule.fragment.album.AlbumFragment;
import com.mediacloud.app.newsmodule.interfaces.AlbumClickCall;
import com.mediacloud.app.newsmodule.model.VideoPlayHistory;
import com.mediacloud.app.newsmodule.model.VideoPlayObj;
import com.mediacloud.app.newsmodule.model.VideoPlayObj.VideoLineItem;
import com.mediacloud.app.newsmodule.model.VideoPlayerListenerImpl;
import com.mediacloud.app.newsmodule.utils.AdDataInvoker;
import com.mediacloud.app.newsmodule.utils.AdDataInvoker.AdDataReciver;
import com.mediacloud.app.newsmodule.utils.AdDataInvoker.AdDataReciver.AdvItemX;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.CollectionUtils;
import com.mediacloud.app.newsmodule.utils.CollectionUtils.ReadNewsItem;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.ShareGridPopUtils;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.reslib.enums.TitileType;
import com.tencent.mmkv.MMKV;

/**
 *
 */
public class AlbumPlayActivity extends BaseBackActivity implements /*OnItemClickListener,*/ DataInvokeCallBack<ArticleItemReciver>/*, ILikesNumUpdate*/ {

    protected boolean isAutoPlay;
    protected VideoPlayer mBaiduPlayer;
    protected View backBtn;
    protected ArticleItem articleItem;
    protected CatalogItem catalogItem;
    protected NewsDetailInvoker newsDetailInvoker;
    protected CatalogItem navigate;
    protected long seekTime = 0;
    protected VideoAdDataCallBack videoAdDataCallBack;
    protected AdDataInvoker adDataInvoker;
    protected NewsLikePresenter newsLikePresenter;
    protected boolean isOutView = false;
    protected View bottomCommentLayout;
    protected AlbumFragment fragment;
    public AlbumClickCall call;

    ShareWrap shareWrap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        videoAdDataCallBack = new VideoAdDataCallBack();
        adDataInvoker = new AdDataInvoker(videoAdDataCallBack);
        newsDetailInvoker = new NewsDetailInvoker(this);
        super.onCreate(savedInstanceState);
        initmBaiduPlayer();
        initBaseViews();
        setNewsTitle();
        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
        showPageTransition();
        shareWrap = new ShareWrap(this,false);
        shareWrap.setShowFunction(true);
    }
    @Override
    protected void moreClicked() {
        super.moreClicked();
        shareWrap.show(mRootView);
       // ShareGridPopUtils.show(this,articleItem,navigate,true,false,mRootView);
    }
    protected void initBaseViews() {
        navigate = getIntent().getParcelableExtra("catalog");
        catalogItem = getIntent().getParcelableExtra("data");
        /**
         * Fragment 回调
         */
        call = new AlbumClickCall() {
            @Override
            public void clickItem(Parcelable p) {
                mBaiduPlayer.stop();
                articleItem = (ArticleItem) p;
                if (articleItem != null) readStatus();
                getVideoDetail();
            }
        };
        /**
         * 初始化Fragment
         */
        fragment = new AlbumFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", catalogItem.getCatid());
        bundle.putString("title", catalogItem.getCatname());
        fragment.setArguments(bundle);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.listContentInfo, fragment);
        transaction.show(fragment);
        transaction.commitNowAllowingStateLoss();
    }

    protected void setNewsTitle() {
        int base=AppFactoryGlobalConfig.getAppServerConfigInfo(this).getBase();
        if(base== TitileType.FRAME)
        {
            setFrameTypeTitle();
        }
        else  if(base== TitileType.NAVIGATE)
        {
            setTitle(navigate!=null?navigate.getCatname():"");
        }
        else  if(base== TitileType.NEWS_TITLE)
        {
            setTitle(catalogItem!=null?catalogItem.getCatname():"");
        }
        else  if(base== TitileType.NOTITLE)
        {
            setTitle("");
        }

    }

    /**
     * 播放器相关初始化
     */
    protected void initmBaiduPlayer() {
        /**
         * 是否自动播放
         */
        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        /**
         * 初始化播放器
         */
        mBaiduPlayer = Utility.findViewById(mRootView, R.id.albumPlayer);
        mBaiduPlayer.hideButtonBack();
        mBaiduPlayer.setNonWifiTipsMainColor(AppFactoryGlobalConfig.getAppServerConfigInfo(this).getMainColor());
        mBaiduPlayer.setDamuEnable(false);
        mBaiduPlayer.setSmallView(View.VISIBLE);
        mBaiduPlayer.stop();
        backBtn = Utility.findViewById(mRootView, R.id.backBtn);
//        backBtn.setVisibility(View.GONE);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBaiduPlayer != null && mBaiduPlayer.isFullScreen()) {
                    mBaiduPlayer.toggleFullScreen();
                    return;
                }
            }
        });
        //initShare();
        float num = 16.0f / 9.0f;
        ViewGroup.LayoutParams layoutParams = mBaiduPlayer.getLayoutParams();
        layoutParams.height = (int) (getResources().getDisplayMetrics().widthPixels / num);
        mBaiduPlayer.setLayoutParams(layoutParams);
        mBaiduPlayer.showLoadingView();
        mBaiduPlayer.setAdCliclkListenter(new AdCliclkListenter() {

            @Override
            public void OnAdCliclkListenter(String LinkUrl, boolean isvideo, AdItem adItem) {
                Log.w(TAG, "adclick:" + LinkUrl);
                ArticleItem articleItem = new ArticleItem();
                articleItem.setLinkNews(false);
                articleItem.setUrl(LinkUrl);
                articleItem.setTitle(getString(R.string.adtitile));
                NewsItemClickUtils.OpenItemNewsHandle(AlbumPlayActivity.this, TypeX.NEWS.LINK, articleItem, null, NeedTokenType.Unnecessary, false, false);
            }
        });

        KillMusicUtils.stopAPS(this);
        //newsLikePresenter = new NewsLikePresenter(this);
    }


    protected void getVideoDetail() {

        String navigate_id = navigate != null ? navigate.getCatid() : "";
        newsDetailInvoker.getArticleById("" + articleItem.getId(), navigate_id);
    }

    protected void getVideoAd4(int type) {
        videoAdDataCallBack.type = type;
        adDataInvoker.getVideoAd("" + articleItem.getCatalogId(), AppFactoryGlobalConfig.getAppServerConfigInfo(this).getAd_host(), getString(R.string.tenantid), type);
    }


    class VideoAdDataCallBack implements DataInvokeCallBack<AdDataReciver> {
        /**
         * 广告类型
         */
        public int type;

        @Override
        public void success(AdDataReciver data) {
            Log.w(TAG, "ad success");
            switch (type) {
                case AdDataInvoker.BufferAd://片头广告请求完再请求片尾广告
                    mBaiduPlayer.clearAdStartItem();
                    if (data.adList != null && data.adList.size() > 0) {
                        mBaiduPlayer.addAdstartItem(data.adList);
                        mBaiduPlayer.setAdStartTotalTime();
                        mBaiduPlayer.toggleFullScreenEnable(true);
                    } else {
                        mBaiduPlayer.toggleFullScreenEnable(false);
                    }
                    getVideoAd4(AdDataInvoker.EndAd);
                    break;
                case AdDataInvoker.PauseAd:
                    if (data.adList != null && data.adList.size() > 0) {
                        AdvItemX advItemX = data.adList.get(0);
                        advItemX.setCanClose(true);
                        mBaiduPlayer.showAdPausevertiseView(advItemX);
                    }
                    break;
                case AdDataInvoker.EndAd://片尾广告请求完了再播放正片
                    mBaiduPlayer.clearAdEndItem();
                    if (data.adList != null && data.adList.size() > 0) {
                        mBaiduPlayer.addAdEndItem(data.adList);
                        mBaiduPlayer.setAdEndTotalTime();
                    }
                    getVideoDetail();
                    break;
            }
        }

        @Override
        public void fault(Object data) {
            Log.w(TAG, "ad fault");
            switch (type) {
                case AdDataInvoker.BufferAd:
                    mBaiduPlayer.toggleFullScreenEnable(false);
                    getVideoAd4(AdDataInvoker.EndAd);
                    break;
                case AdDataInvoker.EndAd:
                    getVideoDetail();
                    break;
            }
        }

    }



    @Override
    public void onBackPressed() {
        boolean value = false;
        if (mBaiduPlayer != null && mBaiduPlayer.isFullScreen()) {
            mBaiduPlayer.toggleFullScreen();
            value = true;
        }
        if (value)
            return;
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        isOutView = true;
        super.onPause();
        if (mBaiduPlayer != null && !isFinish) {
            saveViewHistory();
            mBaiduPlayer.pagePause = true;
            mBaiduPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        isOutView = false;
        super.onResume();
        if (mBaiduPlayer != null) {
            mBaiduPlayer.resume();
            mBaiduPlayer.adResume();
        }
    }

    @Override
    public void finish() {
        super.finish();
        if(readStatusInvoker!=null)
            readStatusInvoker.destory();
        readStatusInvoker=null;
        if (mBaiduPlayer != null) {
            saveViewHistory();
            mBaiduPlayer.stop();
            mBaiduPlayer.onUnregisterReceiver();
        }
//        VideoAudioActivityRunningTask.VideoActivity.clear();
        if (newsDetailInvoker != null) {
            newsDetailInvoker.destory();
        }
        if (adDataInvoker != null) {
            adDataInvoker.destory();
        }
        if (newsLikePresenter != null) {
            newsLikePresenter.addLikeDataInvoke.destory();
        }
    }

    @Override
    public int getStatusBarColor() {
        if (mBaiduPlayer != null && mBaiduPlayer.isFullScreen())
            return Color.TRANSPARENT;
        return super.getStatusBarColor();

    }

    @Override
    public int getLayoutResID() {
        return R.layout.activity_album_play;
    }



    public void setmBaiduPlayerData() {
        mBaiduPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
            @Override
            public void onpause(int currentMediaIndex) {
                super.onpause(currentMediaIndex);
                if (articleItem.getIsAdvertisement() == 1)
                    getVideoAd4(AdDataInvoker.PauseAd);
            }

            @Override
            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
                if(isFullScreen)
                {
                    mTitileBar.setVisibility(View.GONE);
                }
                else
                {
                    mTitileBar.setVisibility(View.VISIBLE);
                }
              //  VideoPlayerCollectionState.setCollectionState(AlbumPlayActivity.this, articleItem, mBaiduPlayer);

            }

            @Override
            public void oncomplete(int currentMediaIndex) {
                super.oncomplete(currentMediaIndex);
                seekTime = 0;
                if (!isFinish)
                    deleteHistoryPosition();
                //				getVideoAd4(AdDataInvoker.EndAd);
            }

            @Override
            public void onstop(int currentMediaIndex) {
                super.onstop(currentMediaIndex);
                if (!isFinish)
                    deleteHistoryPosition();
            }

            @Override
            public void onPrepared(int currentMediaIndex) {
                super.onPrepared(currentMediaIndex);
                mBaiduPlayer.toggleFullScreenEnable(true);
                try {

                    String[] times = articleItem.getProp4().split(":");
                    int hours, min, sec;
                    hours = Integer.valueOf("" + times[0]);
                    min = Integer.valueOf("" + times[1]);
                    sec = Integer.valueOf("" + times[2]);
                    int total = hours * 60 * 60;
                    total += min * 60;
                    total += sec;
                    if (total > 0)
                        mBaiduPlayer.setConfigDuration(total);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                if (seekTime > 0) {
                    mBaiduPlayer.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            if (seekTime >= mBaiduPlayer.getDuration())
                                return;
                            mBaiduPlayer.seek(seekTime);
                            String seek_last_position_tips = getResources().getString(R.string.seek_last_position_tips);
                            seek_last_position_tips += Tools.convertTimeFormat((int) seekTime);
                            seekTime = 0;
                            if (!isOutView)
//                                ToastUtil.show(AlbumPlayActivity.this, seek_last_position_tips, Gravity.CENTER);
                                ToastUtil.showCustomView(AlbumPlayActivity.this, seek_last_position_tips);
                        }
                    }, 1000);
                } else {
                    if (isOutView)
                        stopShareBgPlayBug();
                }
            }

            @Override
            public void onSeekComplete(int currentMediaIndex) {
                super.onSeekComplete(currentMediaIndex);
                if (isOutView)
                    stopShareBgPlayBug();
                seekTime = 0;
            }

            @Override
            public void onVideoComletionAd() {
                super.onVideoComletionAd();
            }
        });
//        mBaiduPlayer.setShareOnItemClick(mBaiduPlayerShareData.getShareItemClickListener(articleItem, this));
    }

    protected final void stopShareBgPlayBug() {
        mRootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isOutView && mBaiduPlayer != null)
                    mBaiduPlayer.pause();
            }
        }, 500);
    }

    protected void deleteHistoryPosition() {
        String extendField = "" + articleItem.extendField;
        if (!TextUtils.isEmpty(extendField)) {
            VideoPlayHistory history = VideoPlayHistory.parse(extendField);
            if (history == null) {
                history = new VideoPlayHistory();
                history.date = DateParse.getNowDate(null);
            }
            history.time = 0L;
            articleItem.extendField = history;
        }
        CollectionUtils.addReadRecord(this, articleItem);
    }

    public void saveViewHistory() {
        if (mBaiduPlayer != null) {
            if (mBaiduPlayer.isComplete()) {
                deleteHistoryPosition();
            } else if (mBaiduPlayer.getcurrentPlayPosition() > 0 && mBaiduPlayer.getcurrentPlayPosition() < mBaiduPlayer.getDuration()) {
                addViewHistory(mBaiduPlayer.getcurrentPlayPosition());
            }
        }
    }

    protected void addViewHistory(long position) {
        VideoPlayHistory history;
        ReadNewsItem readNewsItem = CollectionUtils.getReadItem(this, articleItem);
        if (readNewsItem != null) {
            ArticleItem readArticleItem = ArticleItem.parse(readNewsItem.newsContent);
            history = VideoPlayHistory.parse("" + readArticleItem.extendField);
        } else {
            history = new VideoPlayHistory();
        }
        history.date = DateParse.getNowDate(null);
        if (position > 0)
            history.time = position;
        articleItem.extendField = history.toString();
        articleItem.setParentId(catalogItem.getCatid());
        CollectionUtils.addReadRecord(this, articleItem);
    }

    @Override
    public void success(ArticleItemReciver data) {
        if (data.state && data.articleItem != null) {
            articleItem = data.articleItem;
            shareWrap.init(articleItem,catalogItem);
            if (fragment != null)
                fragment.item = articleItem;
            mBaiduPlayer.setErrorViewVisible(View.GONE);
            mBaiduPlayer.setAutoPlay(isAutoPlay);
            setmBaiduPlayerData();
            if (articleItem.getTitle() != null) {
                mBaiduPlayer.showVideoTitleInfo(articleItem.getTitle());
            }
            try {
                JSONObject video = new JSONObject(articleItem.getVideo());
                String poster = video.optString("poster","");
                mBaiduPlayer.setPoster(poster,AppFactoryGlobalConfig.getDefaultImageLoadDrawable(),AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
                JSONArray tsAddress = VideoAddressGet.getAddress(video);
                VideoPlayObj videoPlayObj = new VideoPlayObj();
                videoPlayObj.setTitle(articleItem.getTitle());
                videoPlayObj.setVID(articleItem.getVid());
                String cdnEncypt = video.optString("cdnConfigEncrypt");
                videoPlayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                videoPlayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
                for (int i = 0;tsAddress!=null&& i < tsAddress.length(); i++) {
                    JSONObject line = tsAddress.optJSONObject(i);
                    VideoLineItem lineItem = new VideoLineItem();
                    lineItem.setAddress(line.optString("url"));
                    lineItem.setQuality(line.optString("title"));
                    lineItem.setCdnEncypt(cdnEncypt);
                    videoPlayObj.getMediaItem().add(lineItem);
                }

                mBaiduPlayer.getMediaObjs().clear();
                mBaiduPlayer.addMediaObjs(videoPlayObj);
                ReadNewsItem readNewsItem = CollectionUtils.getReadItem(this, articleItem);
                if (videoPlayObj.getMediaItem().size() > 0) {
                    if (readNewsItem != null) {
                        ArticleItem readArticleItem = ArticleItem.parse(readNewsItem.newsContent);
                        VideoPlayHistory history = VideoPlayHistory.parse("" + readArticleItem.extendField);
                        mBaiduPlayer.playVideobj(0);
                        if (history.time > 0) {
                            seekTime = history.time;
                            addViewHistory(seekTime);
                        } else {
                            addViewHistory(0);
                            seekTime = 0;
                        }
                    } else {
                        seekTime = 0;
                        mBaiduPlayer.playVideobj(0);
                        addViewHistory(0);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "" + e.getMessage());
                mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
            }
        } else {
            mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
        }
        AddMedalStatistics.addMedalStatistics(this); //勋章统计
        AddIntegralCounter.start(AlbumPlayActivity.this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(AlbumPlayActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    @Override
    public void fault(Object data) {
        mBaiduPlayer.setErrorViewVisible(View.VISIBLE);
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//        super.onActivityResult(requestCode, resultCode, intent);
//        SocialShareControl.onActivityResult(requestCode, resultCode, intent);
//    }

    ReadStatusInvoker readStatusInvoker;
    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(),articleItem,data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(),articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if(articleItem != null){
            AcquisitionManager.getInstance().readEnter(info,""+articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()),articleItem.getUrl(),articleItem.getTitle(),articleItem.getContent());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if(articleItem != null){
            AcquisitionManager.getInstance().readExit(info,""+articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()),articleItem.getUrl(),articleItem.getTitle(),articleItem.getContent());
        }
    }
}